package com.ilibrary.db.dao.hibernate.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.ilibrary.db.dao.MyBaseHibernateDao;
import com.ilibrary.db.dao.hibernate.NewsDao;
import com.ilibrary.db.entity.News;

public class NewsDaoImpl extends MyBaseHibernateDao<News, Integer> implements NewsDao {

	@Override
	public List<News> queryList(final int start, final int limit, final String newsCategoryId, String keywords) {
		List<News> list = null;
		
		try {
			List result = getHibernateTemplate().executeFind(new HibernateCallback() {
				@Override
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					Query query = null;
					if(newsCategoryId == null || newsCategoryId.equals("")) {
						query = session.createQuery("from News n order by n.createDt desc");
					}else {
						query = session.createQuery("from News n where n.newsCategory =:nc order by n.createDt desc");
						query.setString("nc", newsCategoryId);
					}
					query.setFirstResult(start);
					query.setMaxResults(limit);
					return query.list();
				}
			});
			list = result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}

	@Override
	public Integer queryCnt(String newsCategoryId, final String keywords) {
		List<News> list = null;
		try {
			List result = this.getHibernateTemplate().executeFind(new HibernateCallback() {
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query query = session.createQuery("from News n");
					return query.list();
				}
			});
			list = result;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return list.size();
	}

}
